import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
import 'package:ibooks/const/constant.dart';
import 'package:ibooks/model/index.dart';
import 'package:ibooks/service/system.dart';
import 'package:ibooks/utils/db_util.dart';
import 'package:ibooks/widget/icon_button.dart';
import 'package:ibooks/widget/index.dart';

class BookShelfPage extends StatefulWidget {
  @override
  _BookShelfPageState createState() => _BookShelfPageState();
}

class _BookShelfPageState extends State<BookShelfPage> {

  List<Book> _books;
  bool isSelected = false;
  IconData editIcon = Icons.delete_forever;
  final SystemService _service = new SystemService();

  List<int> selectBookIds = [];

  SqlLiteUtil _sqlLiteUtil = new SqlLiteUtil();

  @override
  initState() {
    super.initState();
    _books = [];
    _sqlLiteUtil.initIBookDB().then((d) {
      showBooks();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[100],
      appBar: PreferredSize(
          child: Container(
            child: Column(
              children: <Widget>[
                SizedBox(height: 10,),
                AppBar(
                  backgroundColor: Colors.grey[100],
                  elevation: 0,
                  leading: Container(
                    alignment: Alignment.center,
                    margin: EdgeInsets.only(left: 10),
                    child: Text("读书",
                      style: TextStyle(
                          fontSize: 22,
                          fontWeight: FontWeight.w600
                      ),
                    ),
                  ),
                  title: Container(
                    height: 34,
                    width: 200,
                    alignment: Alignment.centerLeft,
                    child: TextField(
                      enabled: false,
                      textAlign: TextAlign.center,
                      textAlignVertical: TextAlignVertical.center,
                      decoration: InputDecoration(
//                          hintText: "搜索",
                      suffixIcon: Icon(Icons.search, size: 18,),
                          filled: true,
                          fillColor: Colors.white,
                          disabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(17),
                            borderSide: BorderSide(width: 0, color: Colors.transparent)
                          )
                      ),
                    ),
                  ),
                  actions: <Widget>[
                    ActionButton(Icons.add, size: 24, callback: loadFiles,),
                    ActionButton(editIcon, size: 24, callback: editBooks,),
                  ],
                )
              ],
            ),
          ),
          preferredSize: Size.fromHeight(80)
      ),
      body: getBooks(),
    );
  }

  loadFiles() {
    FilePicker.getMultiFilePath(fileExtension: "TXT").then((Map<String, String> map) {
      if (map != null && map.length > 0) {
        map.forEach((k, v) {
          Book book = Book(path: v);
          var split = k.split(".");
          book.type = split[split.length - 1].toUpperCase();
          book.name = k.replaceAll(".${split[split.length - 1]}", "");
          book.process = 0;
          _sqlLiteUtil.insert(book).then((Book book) {
            if (book != null) {
              _books.add(book);
              setState(() {
              });
            }
          });
        });
      }
    });
  }

  getBooks() {
    if (_books == null || _books.length == 0) {
      return Center(
        child: Text("现在书架空空如也~"),
      );
    } else {
      _books.forEach((b) {
        print("book ===> ${b.id}");
      });
      return Container(
        padding: EdgeInsets.all(5),
        child: GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            childAspectRatio: 1 / 1.35,
            mainAxisSpacing: 10
          ),
          itemCount: _books.length,
          itemBuilder: (builder, idx) {
            return BookItem(book: _books[idx], isSelected: isSelected, callback: editBooks,);
          }
        ),
      );
    }
  }

  showBooks() async {
    _sqlLiteUtil.getAllBooks().then((List<Book> books) {
      if (books != null && books.length > 0) {
        books.forEach((b) {
          print("db book ===> ${b.id}");
        });
        setState(() {
          _books = books;
        });
      } else {
        if (_books != null) {
          setState(() {
            _books = [];
          });
        }
      }
    });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _sqlLiteUtil.close();
  }

  editBooks () {
    if (_books == null || _books.length == 0) {
      return;
    }
    setState(() {
      isSelected = !isSelected;
      editIcon = isSelected == true ? Icons.check : Icons.delete_forever;
      if (isSelected) {
        removeSelectedBooks();
      } else {
        _service.setStringList(Constant.selectBookIds, []);
      }
    });
  }

  removeSelectedBooks() async {
    List<int> selectIds = _service.getStringList(Constant.selectBookIds).map(int.parse).toList();
    int res = await _sqlLiteUtil.removeBooksByIds(selectIds);
    if (res != null && res > 0) {
      showBooks();
    }
  }

  removeAllBooks() async {
    int res = await _sqlLiteUtil.removeAllBooks();
    if (res != null && res > 0) {
      showBooks();
    }
  }
}
